﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Activities.Domain.WorkflowInstances;
using Happy.Activities.Domain.Workflows.Internal;

namespace Happy.Activities.Domain.Workflows
{
    /// <summary>
    /// 代表了流程中的一个合流节点。
    /// </summary>
    public class JoinActivity : Activity
    {
        /// <inheritdoc />
        protected internal override ActivityInstance CreateInstance(WorkflowContext context, string routerSplitToken = SplitTokenHelper.DefaultSplitToken)
        {
            var activityInstance = context
                .WorkflowInstance
                .ActivityInstances
                .FirstOrDefault(x => x.ActivityId == this.Id && x.SplitToken == routerSplitToken);

            if (activityInstance == null)
            {
                activityInstance = base.CreateInstance(context, routerSplitToken);
            }

            return activityInstance;
        }

        /// <inheritdoc />
        protected internal override string CreateRouterSplitToken(WorkflowContext context, ActivityInstance activityInstance)
        {
            return SplitTokenHelper.RemoveLastSplitToken(activityInstance.SplitToken);
        }

        /// <inheritdoc />
        protected override bool CanEnter(WorkflowContext context, ActivityInstance activityInstance)
        {
            var splitActivityInstanceId = SplitTokenHelper.GetLastSplitActivityInstanceId(activityInstance.SplitToken);

            var splitCount = context
                .WorkflowInstance
                .RouterInstances
                .Where(x => x.FromInstanceId == splitActivityInstanceId)
                .Count();

            var joinCount = context
                .WorkflowInstance
                .RouterInstances
                .Where(x => x.ToInstanceId == activityInstance.Id)
                .Count();

            return splitCount == joinCount;
        }

        /// <inheritdoc />
        protected override void OnEnter(WorkflowContext context, ActivityInstance activityInstance)
        {
            this.Exit(context, activityInstance);
        }

        /// <inheritdoc />
        protected override bool CanExit(WorkflowContext context, ActivityInstance activityInstance)
        {
            return true;
        }

        /// <inheritdoc />
        protected override void OnExit(WorkflowContext context, ActivityInstance activityInstance)
        {
            var routers = context
                .WorkflowInstance
                .Workflow
                .GetRoutersByFromId(this.Id);

            routers.First().Route(context, activityInstance);
        }
    }
}
